package qy.jalgotrade;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

import org.apache.commons.configuration2.INIConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;

import ch.qos.logback.classic.util.ContextInitializer;
import qy.qyalgotrader.utils.Services;

/**
 * @author qy
 *
 */
public class Initializer {

	public static final String BOOTSTRAP_PROP = "bootstrap.properties";

	public static final String CONF_DIR = "QYJAT_CONF_DIR";

	public static final String LOG_DIR = "QYJAT_LOG_DIR";

	public static final String DEPLOY_INI = "deploy.ini";

	public static final String LOGBACK_XML = "logback.xml";

	public static INIConfiguration APP_DEPLOY_CONFIG;

	static {

		try {
			bootstrap(null);
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			APP_DEPLOY_CONFIG = new Configurations().ini(Paths.get(System.getProperty(CONF_DIR), DEPLOY_INI).toFile());
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args args
	 * @throws IOException IOException
	 */
	public static void main(String[] args) throws IOException {

		bootstrap(args);
	}

	/**
	 * 
	 * @param args args
	 * @throws IOException IOException
	 */
	public static void bootstrap(String[] args) throws IOException {

		// specify conf dir:
		Properties prop = new Properties();
		prop.load(Initializer.class.getClassLoader().getResourceAsStream(BOOTSTRAP_PROP));
		Path confDir = Paths.get((String) prop.get(CONF_DIR));
		String logDir = prop.getProperty(LOG_DIR);
		// set -DQYJAT_CONF_DIR, -DQYJAT_LOG_DIR:
		System.setProperty(CONF_DIR, confDir.toString());
		System.setProperty(LOG_DIR, logDir);

		// set -Dlogback.configurationFile:
		System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, confDir.resolve(LOGBACK_XML).toString());
	}

	/**
	 * 
	 */
	public static void shutdown() {

		Services.getInstance().stop();
	}

	/**
	 * 
	 * @return cwd
	 */
	public static String getCwd() {

		return System.getProperty("user.dir");
	}
}
